package cn.tude.websocket.websocket.controller;

import cn.tude.websocket.websocket.pojo.dto.HistoryQuery;
import cn.tude.websocket.websocket.pojo.entity.Message;
import cn.tude.websocket.websocket.pojo.vo.MessageVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static cn.tude.websocket.websocket.util.WebSocketUtil.*;

@Slf4j
@RestController
@ServerEndpoint(value = "/chat/{id}")
public class WebSocketController {

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session){
        sessions.put(id,session);
        log.debug(id+"已经连接到服务器！");
        //暂时不用返回在线人数
//        List<String> sessList=new ArrayList<>();
//        sessions.forEach((k,v)->{
//            if (!k.equals(id)){
//                sessList.add(k);
//            }
//        });
//        try {
//            //当用户进入聊天页面时 会自动连接websocket服务器 并存储会话     并且以数组形式返回在线用户
//            //如：["10666","90888"]
//            sendMessage(session,jsonMapper.writeValueAsString(sessList));
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
    }

    @OnMessage
    public void onMessage(@PathParam("id") String id,String message,Session session){

            int mao=message.indexOf(":");
            int gan=message.indexOf("-");
            String fromI=message.substring(0,gan);
        System.out.println(gan);
            String toI=message.substring(gan+1,mao);
            if ("".equals(message.substring(mao+1))){
                log.debug("前端发的消息为={}",message);
                HistoryQuery historyQuery=new HistoryQuery();
                historyQuery.setFromId(fromI);
                historyQuery.setToId(toI);
                List<MessageVO> list = webSocketService.getHistory(historyQuery);
                try {
                    String jsonMsg=jsonMapper.writeValueAsString(list);
                    System.out.println(jsonMsg);
                    //当点击某一用户时 客户端向服务器发送一条空字符串信息 携带2个id  例如  10666-90888:   服务器会以数组的形式返回消息记录
                    //如：[{"fromId":90888,"toId":10666,"message":"你好啊"},{"fromId":"10666","toId":"90888","message":"你也好啊"},{"fromId":"10666","toId":"90888","message":"滴滴答答的"},{"fromId":"90888","toId":"10666","message":"你好啊！！！"}]
                    sendMessage(sessions.get(fromI),jsonMsg);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                return;
            }
            if (sessions.get(toI)!=null){
                //遍历所有sessions  看是否存在这一对  存在则不管 不在则添加
                if (!foreachAllfromto(fromI,toI)){
                    form_to_Sessions.put(fromI,toI);
                }
                sendMessage(sessions.get(toI),message);
                Message message1=new Message();
                message1.setFromId(Long.parseLong(fromI));
                message1.setToId(Long.parseLong(toI));
                message1.setMessage(message.substring(mao+1));
                webSocketService.saveMessage(message1);
            }else {
                sendMessage(session,"对方用户不在线！");
                Message message1=new Message();
                message1.setFromId(Long.parseLong(fromI));
                message1.setToId(Long.parseLong(toI));
                message1.setMessage(message.substring(mao+1));
                webSocketService.saveMessage(message1);
            }

    }




    @OnClose
    public void onClose(@PathParam("id") String id,Session session){
        //当用户离线时 会删除服务器session会话对象  并且告知所有在这一次会话中发过消息的人 已经离线
        sessions.remove(id);
        try {
            session.close();
        } catch (IOException e) {
            log.error("关闭出现异常");
        }
        form_to_Sessions.forEach((k,v)->{
            if (k.equals(id)){
                sendMessage(sessions.get(v),"对方用户不在线！");
                form_to_Sessions.remove(k);
            }else if (v.equals(id)){
                sendMessage(sessions.get(k),"对方用户不在线！");
                form_to_Sessions.remove(k);
            }
        });
    }


}
